package com.hispot.download;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by admin on 2016/11/16.
 */
class DataBaseManagerImp extends DataBaseManager{

    SQLiteOpenHelper sqLiteOpenHelper;

    AtomicInteger atomicInteger = new AtomicInteger();

    SQLiteDatabase database;

    public DataBaseManagerImp(SQLiteOpenHelper sqLiteOpenHelper) {
        this.sqLiteOpenHelper = sqLiteOpenHelper;
        if (sqLiteOpenHelper == null) {
            throw new IllegalStateException(SQLiteOpenHelper.class.getSimpleName() +
                    " is null");
        }
    }

    @Override
    public synchronized SQLiteDatabase openDataBase() {
        if (atomicInteger.incrementAndGet() == 1){
            database = sqLiteOpenHelper.getWritableDatabase();
        }
        return database;
    }

    @Override
    public synchronized void closeDataBase() {
        if (atomicInteger.decrementAndGet() == 0){
            database.close();
        }
    }

    @Override
    public synchronized void close() {
        sqLiteOpenHelper.close();
    }
}
